package com.ygxsk.carhome.ui.usercenter;

import static com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions.withCrossFade;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.PictureDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.PathUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.blankj.utilcode.util.UriUtils;
import com.blankj.utilcode.util.Utils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.transition.Transition;
import com.gyf.immersionbar.ImmersionBar;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.hjq.toast.Toaster;
import com.kongzue.dialogx.dialogs.PopTip;
import com.tencent.mmkv.MMKV;
import com.trello.rxlifecycle4.android.ActivityEvent;
import com.yalantis.ucrop.UCrop;
import com.yanzhenjie.album.Action;
import com.yanzhenjie.album.Album;
import com.yanzhenjie.album.AlbumFile;
import com.yanzhenjie.album.api.widget.Widget;
import com.yanzhenjie.durban.Controller;
import com.yanzhenjie.durban.Durban;
import com.ygxsk.carhome.R;
import com.ygxsk.carhome.alertview.AlertView;
import com.ygxsk.carhome.alertview.OnItemClickListener;
import com.ygxsk.carhome.alertview.OperationBean;
import com.ygxsk.carhome.configeng.GifSizeFilter;
import com.ygxsk.carhome.configeng.Glide4Engine;
import com.ygxsk.carhome.constant.ConstantApi;
import com.ygxsk.carhome.constant.ConstantSign;
import com.ygxsk.carhome.constant.ExtraKey;
import com.ygxsk.carhome.event.EventInfo;
import com.ygxsk.carhome.listener.AuthorityCallbackListener;
import com.ygxsk.carhome.listener.DoubleClickListener;
import com.ygxsk.carhome.listener.RxBus;
import com.ygxsk.carhome.response.AvatarBean;
import com.ygxsk.carhome.response.MyInfoQRCode;
import com.ygxsk.carhome.retrofit.AddLogUpLoadInfo;
import com.ygxsk.carhome.retrofit.ApiException;
import com.ygxsk.carhome.retrofit.ApiRequestSubListener;
import com.ygxsk.carhome.retrofit.ApiService;
import com.ygxsk.carhome.retrofit.ErrorConsumer;
import com.ygxsk.carhome.retrofit.NetworkManager;
import com.ygxsk.carhome.retrofit.ResponseTransformer;
import com.ygxsk.carhome.svg.SvgSoftwareLayerSetter;
import com.ygxsk.carhome.sys.PermissionInterceptor;
import com.ygxsk.carhome.sys.PermissionNameConvert;
import com.ygxsk.carhome.sys.Session;
import com.ygxsk.carhome.ui.ErrorActivity;
import com.ygxsk.carhome.utils.CommTools;
import com.ygxsk.carhome.utils.CommUtils;
import com.ygxsk.carhome.utils.TimeUtilSer;
import com.ygxsk.integrated.retrofit.Parameterkey;
import com.zhongjh.albumcamerarecorder.album.filter.BaseFilter;
import com.zhongjh.albumcamerarecorder.listener.OnResultCallbackListener;
import com.zhongjh.albumcamerarecorder.settings.AlbumSetting;
import com.zhongjh.albumcamerarecorder.settings.CameraSetting;
import com.zhongjh.albumcamerarecorder.settings.GlobalSetting;
import com.zhongjh.albumcamerarecorder.settings.MultiMediaSetting;
import com.zhongjh.common.entity.LocalFile;
import com.zhongjh.common.entity.MultiMedia;
import com.zhongjh.common.entity.SaveStrategy;
import com.zhongjh.common.enums.MimeType;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.bingoogolapple.baseadapter.BGABaseAdapterUtil;
import cn.bingoogolapple.photopicker.activity.BGAPhotoPickerActivity;
import cn.bingoogolapple.photopicker.imageloader.BGAImage;
import cn.bingoogolapple.photopicker.util.BGAPhotoHelper;
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.disposables.CompositeDisposable;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.functions.Consumer;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * @date 2018/1/11 0011
 * @auther itchenqi
 * @description 个人中心--我的资料--这里需要上传头像的内容，2023年9月6日08:53:34添加了 该用户的手机号信息，为了看和测试用的
 * <p>
 * 2023-9-6 08:53:56 又补充个人的二维码信息：
 */
public class MyInfoActivity extends ErrorActivity {

    //填充界面的内容以及事件内容
    //@BindView(R.id.layouttouxianginfo)
    //RelativeLayout layouttouxianginfo;

    @BindView(R.id.imageviewheadinfo)
    de.hdodenhof.circleimageview.CircleImageView imageviewheadinfo;

    /**
     * 设置昵称
     */
    //@BindView(R.id.layoutsetnick)
    //RelativeLayout layoutsetnick;

    @BindView(R.id.textviewpersonphonemy)
    TextView textViewPersonPhoneMy;

    /**
     * 设置昵称的值内容
     */
    @BindView(R.id.textviewnickname)
    TextView textviewnickname;


    /**
     * 设置性别
     */
    //@BindView(R.id.layoutsetgender)
    //RelativeLayout layoutsetgender;
    /**
     * 设置性别内容
     */
    @BindView(R.id.textviewnickgender)
    TextView textviewnickgender;


    /**
     * 设置职业
     */
    //@BindView(R.id.layoutsetjob)
    //RelativeLayout layoutsetjob;
    /**
     * 设置职业内容
     */
    @BindView(R.id.textviewjob)
    TextView textviewjob;


    /**
     * 设置星座
     */
    //@BindView(R.id.layoutsetxingzuo)
    //RelativeLayout layoutsetxingzuo;
    /**
     * 设置星座内容
     */
    @BindView(R.id.textviewconstion)
    TextView textviewconstion;


    /**
     * 设置情感状况
     */
    //@BindView(R.id.layoutsetemotion)
    //RelativeLayout layoutsetemotion;
    /**
     * 设置情感状况内容
     */
    @BindView(R.id.textviewemotion)
    TextView textviewemotion;


    /**
     * 设置兴趣爱好
     */
    //@BindView(R.id.layoutsethobby)
    //RelativeLayout layoutsethobby;
    /**
     * 设置兴趣爱好
     */
    @BindView(R.id.textviewhobby)
    TextView textviewhobby;

    @BindView(R.id.textviewinfotruename)
    TextView textviewInfoTrueName;

    //员工端二维码，是下载链接 的下载图片
    @BindView(R.id.imageviewqrcodeforuser)
    ImageView imageViewQRCodeForUser;


    /**
     * 添加设置昵称等文本信息的监听器
     */
    //private Disposable subscriptionInfoModify;


    /**
     * 性别列表信息内容
     */
    final ArrayList<OperationBean> mDatasGender = new ArrayList<>();
    /**
     * 星座内容
     */
    final ArrayList<OperationBean> mDatasXingzuo = new ArrayList<>();

    /**
     * 婚姻状态
     */
    final ArrayList<OperationBean> mDatasEmotion = new ArrayList<>();


    /**
     * 滚轮的标志内容
     */
    private int flag_acion = 0;

    /**
     * 处理nameid上传的信息
     */
    private int nameIdFinal = 0;
    private CompositeDisposable mCompositeDisposable = new CompositeDisposable();

    @OnClick({R.id.layoutsetnick,//昵称
            R.id.layoutsetjob,//职业
            R.id.layoutsethobby,//兴趣爱好
            R.id.layoutsetgender,//性别
            R.id.layoutinfotruename,//姓名
            R.id.layoutsetxingzuo,//星座
            R.id.layoutsetemotion})//情感
    public void ClickinMyinfo(View view) {

        switch (view.getId()) {
            case R.id.layoutsetnick: {//设置昵称

                if (!DoubleClickListener.isFastDoubleClick()) {
                    Bundle bundle = new Bundle();
                    bundle.putInt(ExtraKey.EXTRA_JUMPFROM_WHERE, 0);
                    bundle.putString(ExtraKey.EXTRA_JUMPFROM_CONTENT, textviewnickname.getText().toString().trim());
                    ActivityUtils.startActivity(bundle, MyInfoModifyActivity.class);
                }

                break;
            }

            case R.id.layoutsetjob: {//设置职业,这个是职位信息，汽车项目可以放开；

                if (!DoubleClickListener.isFastDoubleClick()) {
                    Bundle bundle = new Bundle();
                    bundle.putInt(ExtraKey.EXTRA_JUMPFROM_WHERE, 1);
                    bundle.putString(ExtraKey.EXTRA_JUMPFROM_CONTENT, textviewjob.getText().toString().trim());
                    ActivityUtils.startActivity(bundle, MyInfoModifyActivity.class);
                }

                break;
            }

//            case R.id.layoutsethobby: {//设置兴趣爱好
//
//                if (!DoubleClickListener.isFastDoubleClick()) {
//                    Bundle bundle = new Bundle();
//                    bundle.putInt(ConstantApi.EXTRA_JUMPFROM_WHERE, 2);
//                    bundle.putString(ConstantApi.EXTRA_JUMPFROM_CONTENT, textviewhobby.getText().toString().trim());
//                    ActivityUtils.startActivity(bundle, MyInfoModifyActivity.class);
//
//                }
//                break;
//            }

            case R.id.layoutinfotruename: {//设置真实姓名

                if (!DoubleClickListener.isFastDoubleClick()) {

                    Bundle bundle = new Bundle();
                    bundle.putInt(ExtraKey.EXTRA_JUMPFROM_WHERE, 3);
                    bundle.putString(ExtraKey.EXTRA_JUMPFROM_CONTENT, textviewInfoTrueName.getText().toString().trim());
                    ActivityUtils.startActivity(bundle, MyInfoModifyActivity.class);

                }

                break;
            }

            //====底部都是弹出滚轮的=====================================================================

//            case R.id.layoutsetgender: {//设置性别
//
//                //弹出滚轮面板的内容
//                //应该是直白的滚轮效果
//
//                //原始代码
//                //final EditListDialog editListDialog = new EditListDialog(MyInfoActivity.this, "选择性别", mDatasGender);
//                //2018年09月17日做更改
//                final EditListDialog editListDialog = EditListDialog.newInstance("选择性别", mDatasGender);
//                editListDialog.setonCancelListener(new OnDialogCancelClickListener() {
//                    @Override
//                    public void onCancelClick(int position) {
//
//                        if (editListDialog != null) {
//                            //editListDialog.dismiss();
//                            editListDialog.dismissAllowingStateLoss();//可以忽略状态
//                        }
//
//                    }
//                });
//
//                editListDialog.setOnDialogItemClickListener(new OnDialogItemClickListener() {
//
//                    @Override
//                    public void onItemClick(OperationBean position) {
//
//                        if (NetworkUtils.isConnected()) {
//
//                            //int nameId = mDatas.get(position).getNameId();
//                            //String name = mDatas.get(position).getName();
//                            //com.blankj.utilcode.util.ToastUtils.showShort(name);
//                            //LogUtils.d("itchen--"+position.getName());
//                            //int keyContent = position.getNameId();
//
//                            if (editListDialog != null) {
//                                //editListDialog.dismiss();
//                                editListDialog.dismissAllowingStateLoss();//可以忽略状态
//                            }
//
//                            //这里提交性别信息内容
//                            flag_acion = 1;
//                            nameIdFinal = position.getNameId();
//                            method_updateCustomerInfo(position.getNameId(), flag_acion);
//
//                        } else {
//                            ToastUtils.showShort(ConstantSign.NONET);
//                        }
//                    }
//                });
//
//                editListDialog.setCancelable(false);
//                editListDialog.show(getSupportFragmentManager(), "layoutsetgender");
//
//                break;
//            }

//            case R.id.layoutsetxingzuo: {//设置星座
//
//                //原始代码
//                //final EditListDialog editListDialogXingzuo = new EditListDialog(MyInfoActivity.this, "选择星座", mDatasXingzuo);
//                //2019年09月17日做更改
//                final EditListDialog editListDialogXingzuo = EditListDialog.newInstance("选择星座", mDatasXingzuo);
//                editListDialogXingzuo.setonCancelListener(new OnDialogCancelClickListener() {
//                    @Override
//                    public void onCancelClick(int position) {
//
//                        if (editListDialogXingzuo != null) {
//                            //editListDialog.dismiss();
//                            editListDialogXingzuo.dismissAllowingStateLoss();//可以忽略状态
//                        }
//                    }
//                });
//
//                editListDialogXingzuo.setOnDialogItemClickListener(new OnDialogItemClickListener() {
//
//                    @Override
//                    public void onItemClick(OperationBean position) {
//
//                        //int nameId = mDatasXingzuo.get(position).getNameId();
//                        //String name = mDatasXingzuo.get(position).getName();
//                        //com.blankj.utilcode.util.ToastUtils.showShort(name);
//                        //LogUtils.d("itchen--"+position.getName());
//
//                        if (NetworkUtils.isConnected()) {
//
//                            //弹窗内容消失
//                            if (editListDialogXingzuo != null) {
//                                //editListDialog.dismiss();
//                                editListDialogXingzuo.dismissAllowingStateLoss();//可以忽略状态
//                            }
//
//                            flag_acion = 2;
//                            nameIdFinal = position.getNameId();
//                            method_updateCustomerInfo(position.getNameId(), flag_acion);
//
//                        } else {
//                            CommUtils.displayToastShort(MyInfoActivity.this, ConstantApi.NONET);
//                        }
//                    }
//                });
//
//                editListDialogXingzuo.setCancelable(false);
//                editListDialogXingzuo.show(getSupportFragmentManager(), "layoutsetxingzuo");
//
//                break;
//            }

//            case R.id.layoutsetemotion: {//设置情感状态
//
//
//                ////原始代码
//                //final EditListDialog editListDialogEmotion = new EditListDialog(MyInfoActivity.this, "选择情感状况", mDatasEmotion);
//
//                //2019年09月17日做更改
//                final EditListDialog editListDialogEmotion = EditListDialog.newInstance("选择情感状况", mDatasEmotion);
//
//                editListDialogEmotion.setonCancelListener(new OnDialogCancelClickListener() {
//                    @Override
//                    public void onCancelClick(int position) {
//
//                        if (editListDialogEmotion != null) {
//                            //editListDialog.dismiss();
//                            editListDialogEmotion.dismissAllowingStateLoss();//可以忽略状态
//                        }
//
//                    }
//                });
//
//                editListDialogEmotion.setOnDialogItemClickListener(new OnDialogItemClickListener() {
//
//                    @Override
//                    public void onItemClick(OperationBean position) {
//                        //int nameId = mDatasEmotion.get(position).getNameId();
//                        //String name = mDatasEmotion.get(position).getName();
//                        //LogUtils.d("itchen--"+position.getName());
//                        //com.blankj.utilcode.util.ToastUtils.showShort(name);
//
//                        if (NetworkUtils.isConnected()) {
//
//
//                            if (editListDialogEmotion != null) {
//                                //editListDialog.dismiss();
//                                editListDialogEmotion.dismissAllowingStateLoss();//可以忽略状态
//                            }
//
//                            flag_acion = 3;
//                            nameIdFinal = position.getNameId();
//                            method_updateCustomerInfo(position.getNameId(), flag_acion);
//
//                        } else {
//
//                            CommUtils.displayToastShort(MyInfoActivity.this, ConstantApi.NONET);
//                        }
//                    }
//                });
//
//                editListDialogEmotion.setCancelable(false);
//                editListDialogEmotion.show(getSupportFragmentManager(), "layoutsetemotion");
//
//
//                break;
//            }

            default:
                break;
        }


    }

    /**
     * @date 2018/3/1 0001
     * @auther itchenqi
     * @description 修改用户的滚轮信息内容。
     */
    private void method_updateCustomerInfo(int nameID, int _flag) {

        HashMap<String, Object> map = new HashMap<>();
        map.put(Parameterkey.customerId, mSession.getCustomerId());//用户id信息

        if (_flag == 1) {//修改性别信息内容

//            map.put(Parameterkey.sex, nameID);

        } else if (_flag == 2) {//修改星座
//            map.put(Parameterkey.constellation, nameID);

        } else if (_flag == 3) {//修改婚姻状况

//            map.put(Parameterkey.maritalStatus, nameID);

        }

        //LogUtils.d("itchen--->map = " + map);

        AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
        addLogUpLoadInfo.setActivity(mActivityInstance);
        addLogUpLoadInfo.setWhat(ConstantApi.WHAT_UPDATECUSTOMERINFO);//请求数字标识
        addLogUpLoadInfo.setUrlPath(ApiService.updateCustomerInfoUrl);//url地址
        addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);//POST 或者 GET
        addLogUpLoadInfo.setToastToUser(true);//展示给用户的标志
        addLogUpLoadInfo.setHashMapParameter(map);

        //做界面展示给用户的
        NetworkManager.getInstance().initRetrofitRxJava()//
                .create(ApiService.class)//
                .updateCustomerInfo(RequestBody.create(JSON.toJSONString(map, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue), MediaType.parse(ApiService.HEADER_JSON)))//
                .compose(MyInfoActivity.this.bindUntilEvent(ActivityEvent.DESTROY))//
                .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<String>(ConstantApi.IS_ACTIVITY_ITSELF, MyInfoActivity.this) {

                    @Override
                    public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
                        super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);
                    }

                    @Override
                    public void onErrorServerNotSuccessDataResponse(int method, boolean isToastToUser, Activity _activity, String statusCode, String message) {
                        super.onErrorServerNotSuccessDataResponse(method, isToastToUser, _activity, statusCode, message);

                        ToastUtils.showShort(message);

                    }
                }))
                .subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String s) throws Exception {

                        if (flag_acion == 1) {//处理性别接口

//                            mSession.setSex(nameIdFinal);

//                            method_sex(nameIdFinal);//修改本界面

                            //修改个人中心界面内容..其实也可以//直接取出也行
//                            RxBus.getInstance().post(new EventInfo(ConstantApi.RXBUS_MODIFY_SEX, String.valueOf(nameIdFinal)));

                        } else if (flag_acion == 2) {//处理星座接口

//                            mSession.setConstellation(nameIdFinal);

//                            method_constellation(nameIdFinal);

                        } else if (flag_acion == 3) {//处理婚姻状况接口

//                            mSession.setMaritalStatus(nameIdFinal);
//                            method_maritalStatus(nameIdFinal);

                        }

                    }

                }, new ErrorConsumer() {

                    @Override
                    protected void error(ApiException e) {


                    }
                });

    }


    //底部弹窗内容
    private AlertView mAlertView;

    private Session mSession;


    interface PicCallBack {

        void clickCamera(int position);

        void clickAlbum(int position);

    }

    /**
     * 已经废弃的 从拍照 逻辑
     */
    private void methodPicCallBackCamera() {

        Album.camera(MyInfoActivity.this)//
                .image()//
                .filePath(PathUtils.getExternalAppFilesPath() + File.separator + ConstantSign.STARTWITH_AVATAR_FLAG + TimeUtilSer.getNowPic() + ".jpg")
                .onResult(new Action<String>() {
                    @Override
                    public void onAction(@NonNull String result) {
                        //拍照路径内容

                        //Glide展示内
                        takePicture(result);
                    }

                }).onCancel(new Action<String>() {
                    @Override
                    public void onAction(@NonNull String result) {
                        ToastUtils.showShort(StringUtils.getString(R.string.cancelinfo));
                    }

                }).start();

    }

    /**
     * 已经废弃的 从相册选择逻辑
     */
    private void methodPicAlbum() {

        //调用相册选择
        Album.image(MyInfoActivity.this)
                .singleChoice()
                //.requestCode(200)//从相册选择的请求码
                .camera(true)
                .columnCount(3)//单行显示的列数
                //.selectCount(2)//只能选择2张图片
                //.checkedList(mAlbumFiles)
                .widget(Widget.newLightBuilder(MyInfoActivity.this)//自定义的界面可以不要
                        .title("选择图库")//
                        .statusBarColor(Color.BLACK)//
                        .toolBarColor(Color.WHITE)//
                        .mediaItemCheckSelector(Color.WHITE, Color.BLUE)//
                        .bucketItemCheckSelector(Color.WHITE, Color.BLUE)
                        .buttonStyle(Widget.ButtonStyle.newLightBuilder(MyInfoActivity.this)//
                                .setButtonSelector(Color.BLUE, Color.WHITE)//
                                .build()).build())//
                .onResult(new Action<ArrayList<AlbumFile>>() {
                    @Override
                    public void onAction(@NonNull ArrayList<AlbumFile> result) {

                        //mAlbumFiles = result;

                        //LogUtils.d("itchen------>头像 选择 位置--->" + result.get(0).getPath());
                        //itchen------>头像  拍照的 位置--->/storage/emulated/0/Tencent/QQ_Images/43e6a3182618121.jpg
                        //这里是可以 多个位置的
                        //itchen------>头像  拍照的 位置--->/storage/emulated/0/DCIM/tb_image_share_1585490533513.jpg

                        //mAdapter.notifyDataSetChanged(mAlbumFiles);
                        //mTvMessage.setVisibility(result.size() > 0 ? View.VISIBLE : View.GONE);

                        //选择头像这个 只有单张。
                        takePicture(result.get(0).getPath());//图片路径内容
                    }

                })
                .onCancel(new Action<String>() {
                    @Override
                    public void onAction(@NonNull String result) {
                        ToastUtils.showShort(StringUtils.getString(R.string.cancelinfo));
                    }

                })
                .start();

    }


    private PicCallBack picCallBackListener = new PicCallBack() {

        @Override
        public void clickCamera(int position) {

            openMain(position);

        }

        @Override
        public void clickAlbum(int position) {

            //不论是不是小米品牌手机，都走该逻辑。
            openMain(position);

        }

    };

    /**
     * @date 2018/1/31 0031
     * @auther itchenqi
     * @description 对图片做剪裁内容
     */
    private void takePicture(String pathString) {

        //LogUtils.d("itchen---->填入准备裁剪的图片的位置==>" + pathString);

        //相册选择的路径：
        //itchen---->填入准备裁剪的图片的位置==>/storage/emulated/0/Pictures/Screenshots/Screenshot_20201211_135446_com.dgj.propertysmart.jpg
        //拍照的路径
        //itchen---->填入准备裁剪的图片的位置==>/storage/emulated/0/Android/data/com.dgj.propertysmart/files/avatar2020_12_11_14_14_43_023.jpg

        //String cropDirectory = CommUtils.getAppRootPath(this).getAbsolutePath();
        //LogUtils.d("itchen---->裁剪图片的位置是--->"+cropDirectory);
        //itchen---->裁剪图片的位置是--->/data/user/0/com.dgj.propertysmart/files

        //对图片做裁剪内容
        Durban.with(this)
                .title("裁剪图库")
                .statusBarColor(ContextCompat.getColor(Utils.getApp(), R.color.black))
                .toolBarColor(ContextCompat.getColor(Utils.getApp(), R.color.gray13))
                .navigationBarColor(ContextCompat.getColor(Utils.getApp(), R.color.black))
                .inputImagePaths(pathString)
                // 图片输出文件夹路径。
                .outputDirectory(PathUtils.getExternalAppFilesPath())
                // Image size limit.
                .maxWidthHeight(500, 500)
                // Aspect ratio.
                .aspectRatio(1, 1)
                // Output format: JPEG, PNG.
                .compressFormat(Durban.COMPRESS_JPEG)
                // Compress quality, see Bitmap#compress(Bitmap.CompressFormat, int, OutputStream)
                .compressQuality(90)
                // Gesture: ROTATE, SCALE, ALL, NONE.
                .gesture(Durban.GESTURE_ALL)
                .controller(Controller.newBuilder()
                        .enable(false)
                        .rotation(true)
                        .rotationTitle(true)
                        .scale(true)
                        .scaleTitle(true)
                        .build())
                .requestCode(300)
                .start();

        //裁剪完毕之后上传该裁剪之后的图片信息：
        //String picFinalPath = Durban.g;
        /*GlideApp.with(MyInfoActivity.this)
                .asBitmap()
                .load(new File(pathString))
                .centerCrop()
                //.transition(withCrossFade())
                .into(new BitmapImageViewTarget(imageviewheadinfo) {

                    @Override
                    protected void setResource(Bitmap resource) {
                        super.setResource(resource);
                        //圆角图片代码。
                    }
                });*/

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {

        LogUtils.d("itchen---读取到了该界面的----->onActivityResult-------onActivityResult");

        if (intent == null) {
            LogUtils.d("itchen---读取到了该界面的----->data-是空的");
            return;
        }

        //--------------------------------------------------------------------------------------------------------------------------

        //用户没有进行有效的设置操作，返回
        if (resultCode == RESULT_CANCELED) {
            ToastUtils.showShort(StringUtils.getString(R.string.cancelopera));
            return;
        }

        //------------------------------------------------------------------------------------------------------------------------
        if (resultCode != RESULT_OK) {
            LogUtils.d("itchen---读取到了该界面的----->onActivityResult----resultCode-不是 RESULT_OK--->" + resultCode);
            return;
        }

        //------------------------------------------------------------------------------------------------------------------------
        switch (requestCode) {

            //ucrop的裁剪
            case UCrop.REQUEST_CROP: {

                //&& requestCode == UCrop.REQUEST_CROP
                final Uri resultUri = UCrop.getOutput(intent);

                if (resultUri != null && resultUri.getScheme().equals("file")) {

//            if (resultUri != null) {

                    try {

//                    copyFileToDownloads(getIntent().getData());
                        String imagePath = resultUri.getPath();

                        LogUtils.d(ConstantSign.LOGCAT_NOMAL + "ucrop裁剪之后的imagePath-->" + imagePath);
//                       itchen-->imagePath-->/storage/emulated/0/Android/data/com.ygxsk.carhome/files/2023_11_23_14_09_51_360.jpg
                        //itchen-->imagePath-->/storage/emulated/0/Android/data/com.ygxsk.carhome/files/2023_11_23_14_14_09_679.jpg
                        //itchen-->imagePath-->/storage/emulated/0/Android/data/com.ygxsk.carhome/files/2023_11_23_19_16_16_693.jpg
                        //itchen-->imagePath-->/storage/emulated/0/Android/data/com.ygxsk.carhome/files/2023_11_23_19_16_16_693.jpg
                        //itchen-->ucrop裁剪之后的imagePath-->/storage/emulated/0/Android/data/com.ygxsk.carhome/files/2024_01_25_08_22_58_113.png

                        //上传图片内容？
                        //展示图片
//                        method_handler_idCardImage(imagePath);

                        method_uploadNoHttp(imagePath);

                    } catch (Exception e) {

//                    Toast.makeText(ResultActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                        if (e != null) {
                            LogUtils.d(ConstantSign.LOGCAT_NOMAL, e.getLocalizedMessage());
                        }

                    }

                } else {
//                Toast.makeText(ResultActivity.this, getString(R.string.toast_unexpected_error), Toast.LENGTH_SHORT).show();
                    ToastUtils.showShort("执行异常~");
                    LogUtils.d(ConstantSign.LOGCAT_NOMAL + "imagePath-->" + "执行异常");
                }

                break;
            }

            //普通的是300 的请求吗
            case 300: {

                //不再创建变量一次填充
                if (!Durban.parseResult(intent).isEmpty()) {

                    //如果是拍照上传的话,能走到这里就说明 相机拍照的 那个图片是拍照成功的
                    //图片裁剪的位置 为：
                    //LogUtils.d("itchen----图片裁剪之后的即将上传的 位置--->" + Durban.parseResult(intent).get(0));
                    //itchen----图片裁剪之后的位置--->/storage/emulated/0/Android/data/com.dgj.propertysmart/files/20201211_1420750641.JPEG

                    //启用上传图片接口信息:
                    method_uploadNoHttp(Durban.parseResult(intent).get(0));

                } else {
                    //LogUtils.d("itchen----->没有取到 图片的信息 ");
                    ToastUtils.showShort(StringUtils.getString(R.string.nopictureinfo));
                }

                break;
            }

            case RC_CHOOSE_PHOTO: {

                ArrayList<String> imageList = BGAPhotoPickerActivity.getSelectedPhotos(intent);

                if (imageList != null && !imageList.isEmpty()) {

                    String imageSingle = imageList.get(0);

//                    LogUtils.d(ConstantSign.LOGCAT_NOMAL + "单个图片信息--->" + imageSingle);
                    //itchen-->单个图片信息--->/storage/emulated/0/DCIM/Screenshots/Screenshot_2023-06-26-14-24-35-269_com.android.browser.jpg

                    // TODO: 2023-08-05 09:45 这里可以还做一层裁剪，我暂时不裁剪；
                    if (!TextUtils.isEmpty(imageSingle)) {

                        //不裁剪直接上传的，这种可行，只是导致图片比较大。
//                        method_uploadNoHttp(imageSingle);

                        //对图片添加裁剪
                        takePictureUCrop(imageSingle);

                    }
                }

                break;
            }

            case CODE_GALLERY_REQUEST: {

                cropRawPhoto(intent.getData());

                break;
            }

            case CODE_RESULT_REQUEST: {

                /*if (intent != null) {
                    setImageToHeadView(intent);    //此代码在小米有异常，换以下代码
                }*/

                try {


                    /*Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(mUriPath));
                    setImageToHeadView(intent, bitmap);*/

                    File file = UriUtils.uri2File(mUriPath);
                    //LogUtils.d("itchen---针对小米机型：选择图像是---->" + file.getPath());
                    //itchen---针对小米机型：选择图像是---->/storage/emulated/0/1587801536580bala_crop.jpg
                    //itchen---针对小米机型：选择图像是---->/storage/emulated/0/Android/data/com.dgj.propertysmart/files/2020-04-25-16-08-59.jpg

                    if (file != null) {
                        method_uploadNoHttp(file.getPath());
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }

                break;
            }

            case REQUEST_CODE_TAKE_PHOTO: {

                try {

                    if (mPhotoHelper != null) {

                        String imagePathResult = mPhotoHelper.getCameraFilePath();

                        ToastUtils.showShort("拍照成功：" + imagePathResult);
                        LogUtils.d(ConstantSign.LOGCAT_NOMAL + "imagePathResult-->" + imagePathResult);
                        //itchen-->imagePathResult-->/storage/emulated/0/Android/data/com.ygxsk.carhome/files/BGAPhotoPickerTakePhoto/Capture_2024-01-23_05-41_171937659510054976125.jpg

                        if (!TextUtils.isEmpty(imagePathResult)) {

                            //startActivityForResult(mPhotoHelper.getCropIntent(imagePathResult, 200, 200), REQUEST_CODE_CROP);

                            takePictureUCrop(imagePathResult);

                            //直接裁剪图片

                        }

                    }

                } catch (Exception e) {

                    mPhotoHelper.deleteCameraFile();
                    mPhotoHelper.deleteCropFile();

//                    BGAPhotoPickerUtil.show(R.string.bga_pp_not_support_crop);
//                    ToastUtils.showShort("不支持裁剪");

                    ToastUtils.showShort(getResources().getString(R.string.bga_pp_not_support_crop));

                    if (e != null) {
                        LogUtils.d(ConstantSign.LOGCAT_NOMAL + "e的裁剪报错内容是-->" + e.getLocalizedMessage());
                    }

                    e.printStackTrace();

                }

                break;
            }

            case REQUEST_CODE_CROP: {

                if (imageviewheadinfo != null) {

                    String imagePathUpLoad = mPhotoHelper.getCropFilePath();
                    LogUtils.d(ConstantSign.LOGCAT_NOMAL + "imagePathUpLoad=>" + imagePathUpLoad);

                    BGAImage.display(imageviewheadinfo, R.drawable.icon_errorfang, imagePathUpLoad, BGABaseAdapterUtil.dp2px(200));

                    method_uploadNoHttp(imagePathUpLoad);

                }

                break;
            }

            default:
                break;
        }

        super.onActivityResult(requestCode, resultCode, intent);

    }

    /**
     * @date 2018/1/31 0031
     * @auther itchenqi
     * @description 对图片做剪裁内容
     */
    private void takePictureUCrop(String pathString) {

        //填充
//        UCrop uCrop = UCrop.of(Uri.fromFile(new File(pathString)), Uri.fromFile(new File(getCacheDir(), "SampleCropImage")));
//        UCrop uCrop = UCrop.of(Uri.fromFile(new File(pathString)), Uri.fromFile(new File(PathUtils.getExternalAppFilesPath(), "SampleCropImage")));
        UCrop uCrop = UCrop.of(Uri.fromFile(new File(pathString)), Uri.fromFile(new File(
                PathUtils.getExternalAppFilesPath() +//
                        File.separator + TimeUtilSer.getNowPic() + //
                        Parameterkey.png)));//

//        uCrop = basisConfig(uCrop);
        uCrop = CommTools.advancedConfig(uCrop);

        uCrop.start(MyInfoActivity.this);

    }

    /**
     * 单独的上传头像的接口内容
     */
    private void method_uploadNoHttp(String _filePath) {

        /*String uploadUrl = Constants.getInstance().uploadPhotoUrl();

        //2018年06月25日做表单上传修改
        Request<String> requestUpload = new StringRequest(uploadUrl, RequestMethod.POST);

        //适合图片上传
        FileBinary fileBinary = new FileBinary(new File(_filePath));
        requestUpload.add("customerId", mSession.getCustomerId());
        requestUpload.add("imageFile", fileBinary);
        requestUpload.setMultipartFormEnable(true);

        //普通的表单提交
        //requestUpload.setMultipartFormEnable(true);

        startRequest(ConstantApi.WHAT_UPLOADURL, requestUpload, httpListenerUpload, true, true);*/

        HashMap<String, Object> map = new HashMap<>();
        map.put(Parameterkey.customerId, mSession.getCustomerId());

        //FileBinary fileBinary = new FileBinary(new File(_filePath));

        //强制以表单形式提交，单个图片内容
//        FormBody formBody = FormBody.newBuilder()//
//                .param("customerId", mSession.getCustomerId())//
//                .file("imageFile", new File(_filePath))//
//                .build();

        MultipartBody.Builder multipartBodybuilder = new MultipartBody.Builder()//
                .setType(MultipartBody.FORM)
                .addFormDataPart(Parameterkey.customerId, mSession.getCustomerId());
        //.file("imageFile", new File(_filePath))//
//        RequestBody requestBodyUpload = new MultipartBody.Builder()
//                //.addFormDataPart()//小区ID


        //for (String path : addLogList) {//图片的路径
        File file = new File(_filePath);
        //RequestBody requestBodyImages = RequestBody.create(file,MediaType.parse("multipart/form-data"));
        //RequestBody requestBodyImages = RequestBody.create(file, MediaType.parse(ApiService.MEDIATYPE_IMAGE_JPG));
        //合并的写
        multipartBodybuilder.addFormDataPart(Parameterkey.imageFile, file.getName(), RequestBody.create(file, MediaType.parse(ApiService.MEDIATYPE_IMAGE_JPG)));
        RequestBody requestBody = multipartBodybuilder.build();

        //MultipartBody.Part parts = multipartBodybuilder.build().part(0);

        AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
        addLogUpLoadInfo.setActivity(mActivityInstance);
        addLogUpLoadInfo.setWhat(ConstantApi.WHAT_UPLOADURL);//请求数字标识
        addLogUpLoadInfo.setUrlPath(ApiService.uploadPhotoUrl);//url地址
        addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);//POST 或者 GET
        addLogUpLoadInfo.setToastToUser(true);//展示给用户的标志
        addLogUpLoadInfo.setHashMapParameter(map);

        //做界面展示给用户的
        NetworkManager.getInstance().initRetrofitRxJava()
                .create(ApiService.class)
                .uploadPhoto(requestBody)
                .compose(MyInfoActivity.this.bindUntilEvent(ActivityEvent.DESTROY))//
                .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<AvatarBean>(ConstantApi.IS_ACTIVITY_ITSELF, MyInfoActivity.this) {
                    @Override
                    public void onErrorServerNotSuccessDataResponse(int method, boolean isToastToUser, Activity _activity, String statusCode, String message) {
                        super.onErrorServerNotSuccessDataResponse(method, isToastToUser, _activity, statusCode, message);
                        CommUtils.checkMaterialDialog(materialDialog);
                        //可能有其他 错误项的处理
                        ToastUtils.showShort(message);
                    }
                })).doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Throwable {
                        method_create_materialDialog(MyInfoActivity.this, ConstantSign.TIPS_SUBMIT);
                    }
                })
                .subscribe(new Consumer<AvatarBean>() {
                    @Override
                    public void accept(AvatarBean avatarBean) throws Exception {

                        CommUtils.checkMaterialDialog(materialDialog);

//                        {
//                            "code":"20000",
//                                "data":{
//                            "largeUrlSuffix":"",
//                                    "smallUrlSuffix":"",
//                                    "url":"http://222.222.17.184:8990/resource//image/photo/20230805/2023080509464245336098.jpg",
//                                    "urlPrefix":"http://222.222.17.184:8990/resource/",
//                                    "urlSuffix":"/image/photo/20230805/2023080509464245336098.jpg"
//                            },
//                            "message":"success"
//                        }

                        if (avatarBean != null) {

                            mSession.setPhotoUrl(avatarBean.getUrl());

                            // TODO: 2023-08-05 09:53 新增的逻辑，图像变动，也相应的修改首页头像


                            //LogUtils.d("itchen--->上传完毕之后的头像 服务器 内容Url地址=" + avatarBean.getUrl());

                            //中间还有 前缀后缀等。暂时不需要保存，用到的时候保存。。
                            method_touxiang(avatarBean.getUrl());//该界面-该界面修改头像

                            //-----------------------------------------------------------------------------
                            // TODO: 2024/1/23 9:48 模拟器测试时候发现图片上传完毕，从相册选择的就删除了图片，不合理，应该是只删除拍照的，相册内选择不删除。
                            //头像上传完毕，删除掉本地生成的图片的 缓存在本地9999
//                            if (!TextUtils.isEmpty(_filePath)) {
//
//                                if (FileUtils.isFileExists(_filePath) && FileUtils.isFile(_filePath)) {
//                                    FileUtils.delete(_filePath);
//                                }
//
//                                //做测试，
//                                        /*boolean currentState = FileUtils.delete(_filePath);
//                                        if (currentState) {
//                                            LogUtils.d("itchen--->删除的图片的地址是-->" + _filePath);
//                                            //itchen--->删除的图片的地址是-->/storage/emulated/0/Android/data/com.dgj.propertysmart/files/20201211_14322608742.JPEG
//                                        }*/
//                            }

                            //-----------------------------------------------------------------------------

                            //删除 avatar 开头的文件. 这样就过滤掉了 是因为相机拍照产生的图片
//                            FileUtils.deleteFilesInDirWithFilter(PathUtils.getExternalAppFilesPath(), new FileFilter() {
//                                @Override
//                                public boolean accept(File pathname) {
//                                    //LogUtils.d("itchen---Android/data/com.dgj.propertysmart/files/文件夹下--->pathname-->" + pathname.getAbsolutePath());
//                                    return pathname.isFile() && pathname.getName().startsWith(ConstantSign.STARTWITH_AVATAR_FLAG);
//                                }
//                            });

                            //-----------------------------------------------------------------------------

                        } else {
                            ToastUtils.showShort(ConstantSign.NET_BAD);
                        }

                    }

                    //自定义

                }, new ErrorConsumer() {

                    @Override
                    protected void error(ApiException e) {

                        CommUtils.checkMaterialDialog(materialDialog);

                        function_apiException(e);

                    }
                });

    }


    private void setPicCallBackListener(PicCallBack picCallBack) {
        this.picCallBackListener = picCallBack;
    }


    //private Rationale mRationale;
//    private PermissionSetting mSetting;
    //private ArrayList<AlbumFile> mAlbumFiles;
    //private String mExtStorDir;

    private static final int REQUEST_CODE_TAKE_PHOTO = 2;
    private static final int REQUEST_CODE_CROP = 3;

    private BGAPhotoHelper mPhotoHelper;
    private File takePhotoDir;

    private GlobalSetting mGlobalSetting;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mActivityInstance = this;

        /*if (arrayListPermission == null) {
            arrayListPermission = new ArrayList<String>();
        }

        arrayListPermission.addAll(Arrays.asList(Permission.CAMERA));
        arrayListPermission.addAll(Arrays.asList(Permission.STORAGE));*/

        //mRationale = new DefaultRationale();

//        mSetting = new PermissionSetting(this);

        //mExtStorDir = Environment.getExternalStorageDirectory().toString();
        //LogUtils.d("itchen---->获取的本地图片存放位置：----mExtStorDir---->"+mExtStorDir);
        //itchen---->获取的本地图片存放位置：----mExtStorDir---->/storage/emulated/0


        mSession = Session.get(this);

        //三个滚轮列表的数据处理

        //性别内容================================================================
        mDatasGender.add(new OperationBean(1, "男"));
        mDatasGender.add(new OperationBean(2, "女"));
        mDatasGender.add(new OperationBean(3, "保密"));

        //星座内容================================================================
        mDatasXingzuo.add(new OperationBean(1, "白羊座"));
        mDatasXingzuo.add(new OperationBean(2, "金牛座"));
        mDatasXingzuo.add(new OperationBean(3, "双子座"));
        mDatasXingzuo.add(new OperationBean(4, "巨蟹座"));
        mDatasXingzuo.add(new OperationBean(5, "狮子座"));
        mDatasXingzuo.add(new OperationBean(6, "处女座"));
        mDatasXingzuo.add(new OperationBean(7, "天秤座"));
        mDatasXingzuo.add(new OperationBean(8, "天蝎座"));
        mDatasXingzuo.add(new OperationBean(9, "射手座"));
        mDatasXingzuo.add(new OperationBean(10, "摩羯座"));
        mDatasXingzuo.add(new OperationBean(11, "水瓶座"));
        mDatasXingzuo.add(new OperationBean(12, "双鱼座"));

        //婚姻状态内容================================================================
        mDatasEmotion.add(new OperationBean(1, "单身"));
        mDatasEmotion.add(new OperationBean(2, "恋爱中"));
        mDatasEmotion.add(new OperationBean(3, "已婚"));
        mDatasEmotion.add(new OperationBean(4, "保密"));


        //刚创建界面的时候填充一次登录接口内的信息================================================================
        //initToolBar("我的资料");

        initViews();

        if (mCompositeDisposable == null) {
            mCompositeDisposable = new CompositeDisposable();
        }

        //修改资料信息的内容RxBus的内容 可以暂时不添加。
        mCompositeDisposable.add(RxBus.getInstance().toObserverable(EventInfo.class)//
                .subscribeOn(AndroidSchedulers.mainThread())//
                .observeOn(AndroidSchedulers.mainThread())//
                .subscribe(new Consumer<EventInfo>() {
                    @Override
                    public void accept(EventInfo eventInfo) throws Exception {

                        int actionFlag = eventInfo.getActionFlag();
                        String messageContent = eventInfo.getMsg();

                        if (actionFlag == ConstantApi.RXBUS_MODIFY_NICKNAME) {//昵称

                            CommUtils.setText(textviewnickname, messageContent);

                        } else if (actionFlag == 1) {//职业

                            CommUtils.setText(textviewjob, messageContent);

                        } else if (actionFlag == 2) {//兴趣爱好

                            CommUtils.setText(textviewhobby, messageContent);

                        } else if (actionFlag == 3) {//设置真实姓名也就是：姓名项

                            CommUtils.setText(textviewInfoTrueName, messageContent);

                        }

                    }
                }));


        //下载头像信息
        //String url = "http://192.168.0.191:81/resource/null/20180310/2018031014500000214318.jpg";
        //new SaveImageTask(MyInfoActivity.this).execute(url);

        takePhotoDir = new File(PathUtils.getExternalAppFilesPath(), "BGAPhotoPickerTakePhoto");
        mPhotoHelper = new BGAPhotoHelper(takePhotoDir);

    }

    @Override
    public Resources getResources() {
        return super.getResources();
    }

    /**
     * Created by csonezp on 16-1-12.
     * 为了测试在该界面的图片异步下载内容。
     */
    /*public class SaveImageTask extends AsyncTask<String, Void, File> {
        private
        final Context context;

        public SaveImageTask(Context context) {
            this.context = context;
        }

        @Override
        protected File doInBackground(String... params) {
            String url = params[0]; // should be easy to extend to share multiple images at once
            try {
                return Glide
                        .with(context)
                        .load(url)
                        .downloadOnly(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
                        .get() // needs to be called on background thread
                        ;
            } catch (Exception ex) {
                return null;
            }
        }

        @Override
        protected void onPostExecute(File result) {

            if (result == null) {
                return;
            }

            String path = result.getPath();//这个下载到缓存中了。

            FileUtils.copyFile(result.getPath(), Environment.getExternalStorageDirectory().getAbsolutePath() + "999.jpg", null);
            LogUtils.d("itchen---图片下载到==" + path);
        }
    }*/
    @Override
    protected void onResume() {
        super.onResume();
        mSession = Session.get(this);
    }

    /**
     * 性别
     */
    private void method_sex(int nameid) {

        for (OperationBean perationBean : mDatasGender) {

            if (nameid == perationBean.getNameId()) {

                //setInfoText
                CommUtils.setText(textviewnickgender, perationBean.getName());
                //textviewnickgender.setText(perationBean.getName());//原始可用代码
                break;
            } else {
                //
            }
        }
    }

    /**
     * 星座
     */
    private void method_constellation(int nameid) {//如果发现没有该条nameid就循环过去了

        for (OperationBean perationBean : mDatasXingzuo) {

            if (nameid == perationBean.getNameId()) {

                CommUtils.setText(textviewconstion, perationBean.getName());
                //textviewconstion.setText(perationBean.getName());//原始可用代码
                break;
            }
        }
    }

    /**
     * 婚姻状态
     */
    private void method_maritalStatus(int nameid) {

        for (OperationBean perationBean : mDatasEmotion) {

            if (nameid == perationBean.getNameId()) {

                //setInfoText
                CommUtils.setText(textviewemotion, perationBean.getName());
                //textviewemotion.setText(perationBean.getName());//原始可用代码。

                break;
            }
        }
    }


    /**
     * 设置头像内容
     */
    private void method_touxiang(String imagePhotoUrl) {

        //String imagePhotoUrl = mSession.getPhotoUrl();

        if (!TextUtils.isEmpty(imagePhotoUrl)) {

            //用户进来肯定是加载链接内的图片
            Glide.with(MyInfoActivity.this)
                    .load(imagePhotoUrl)
                    .skipMemoryCache(true)//跳过内存缓存
                    .diskCacheStrategy(DiskCacheStrategy.NONE)//不在磁盘中缓存
                    .placeholder(R.drawable.defaulttoub)//
                    .error(R.drawable.defaulttoub)//
                    .fallback(R.drawable.defaulttoub)//
                    .centerCrop()
                    //.transition(withCrossFade())
                    .into(new CustomTarget<Drawable>() {
                        @Override
                        public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
                            //手动指定图片内容
                            imageviewheadinfo.setImageDrawable(resource);
                        }

                        @Override
                        public void onLoadCleared(@Nullable Drawable placeholder) {

                        }
                    });
        } else {

            Glide.with(MyInfoActivity.this)//
                    .load(R.drawable.defaulttoub)//
                    .skipMemoryCache(true)//跳过内存缓存
                    .diskCacheStrategy(DiskCacheStrategy.NONE)//不在磁盘中缓存
                    .placeholder(R.drawable.defaulttoub)//
                    .error(R.drawable.defaulttoub)//
                    .fallback(R.drawable.defaulttoub)//
                    .centerCrop()
                    //.transition(withCrossFade())
                    .into(new CustomTarget<Drawable>() {
                        @Override
                        public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
                            //手动指定图片内容
                            imageviewheadinfo.setImageDrawable(resource);
                        }

                        @Override
                        public void onLoadCleared(@Nullable Drawable placeholder) {

                        }
                    });

        }


    }


    @Override
    protected int getContentViewId() {
        return R.layout.activity_my_info;
    }

//    @Override
//    protected void setStatusBar() {
//
//        //尽量保持状态栏是主题的白色
//        //BarUtils.setStatusBarColor(this, ColorUtils.getColor(R.color.white));
//        BarUtils.setStatusBarColor(this, ColorUtils.getColor(R.color.white));
//        //这样可以保证状态栏是透明的并且文字是黑色
//        BarUtils.setStatusBarLightMode(this, true);
//        //设置然哪个界面
//        BarUtils.addMarginTopEqualStatusBarHeight(this.findViewById(R.id.myinfoactivityoutside));
//
//
//    }

    @Override
    protected void initImmersionBar() {
        super.initImmersionBar();

        ImmersionBar.with(this)//
                .titleBar(R.id.toolbarygxskout)
                .fitsSystemWindows(true)//解决状态栏和布局重叠问题，任选其一，默认为false，当为true时一定要指定statusBarColor()，不然状态栏为透明色，还有一些重载方法
                //.statusBarColor(R.color.colorPrimary)//
                //.navigationBarColor(R.color.colorPrimary)//
                //.keyboardEnable(true)
                .init();

    }

    @Override
    protected void initToolBar(ToolbarHelper toolbarHelper) {

//        toolbarHelper.setLayoutSao(false, null);
        toolbarHelper.setTitle(getString(R.string.title_myinfo));
        toolbarHelper.setVersionName(true, AppUtils.getAppVersionName());
        toolbarHelper.setLayoutLeft(true, R.drawable.backicon, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                methodBack();
            }
        });

        toolbarHelper.setLayoutClose(false, "", null);
        toolbarHelper.setLayoutRight(false, 0, "", null);

    }


    @Override
    public void onClickNodata(View v) {

        //retain暂时用不到

    }


    @Override
    public void initViews() {
        //加载头像内容=================================================================
        //先添加上如果不要就关闭
//        imageviewheadinfo.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//
//                ArrayList<String> arrayList = new ArrayList<>();
//                arrayList.add(mSession.getPhotoUrl());
//
//                Album.gallery(MyInfoActivity.this)//
//                        .requestCode(2)//
//                        .checkedList(arrayList)//
//                        .navigationAlpha(80)//
//                        .checkable(false)//是否出现选择对勾内容//
//                        .widget(//
//                                Widget.newDarkBuilder(MyInfoActivity.this)
//                                        .title("头像")//
//                                        .build()//
//                        )
//                        .onResult(new Action<ArrayList<String>>() {
//                            @Override
//                            public void onAction(@NonNull ArrayList<String> result) {
//
//                            }
//
//                            @Override
//                            public void onAction(int requestCode, @NonNull ArrayList<String> result) {
//
//                            }
//                        })
//                        .start();
//            }
//        });

        //用户的手机号;
        CommUtils.setText(textViewPersonPhoneMy, MMKV.defaultMMKV().decodeString(ConstantSign.P_USERPHONE));

        method_touxiang(mSession.getPhotoUrl());

        //设置昵称等信息setInfoText=================================================================
        CommUtils.setText(textviewnickname, mSession.getNickName());//setInfoText

        //设置真实姓名
        CommUtils.setText(textviewInfoTrueName, mSession.getTrueName());

        //性别
//        method_sex(mSession.getSex());//没有设置性别，默认是3

        //职业setInfoText
        CommUtils.setText(textviewjob, mSession.getOccupation());

        //星座
//        method_constellation(mSession.getConstellation());

        //情感状况
//        method_maritalStatus(mSession.getMaritalStatus());

        //兴趣爱好setInfoText
//        CommUtils.setText(textviewhobby, mSession.getHobby());
        //================================================================================


        //选择图片的监听器========================================================
        //设置监听放在最后：
        this.setPicCallBackListener(picCallBackListener);


        //下载员工端的二维码图片链接
        gainDatas();


    }

    private void initQRCodeForUser(String _imageUrlQRCode) {

        if (!TextUtils.isEmpty(_imageUrlQRCode)) {

            if (_imageUrlQRCode.endsWith(ConstantSign.SVG_POSTFIX)) {

//                LogUtils.d(ConstantSign.LOGCAT_NOMAL + _imageUrlQRCode);

                Glide.with(MyInfoActivity.this)
                        .as(PictureDrawable.class)
                        //.placeholder(R.drawable.icon_errorfang)//原始使用这个占位图
                        .error(R.drawable.icon_errorfang)//
                        .transition(withCrossFade())//
                        .listener(new SvgSoftwareLayerSetter())//
                        .load(_imageUrlQRCode)//动态取出
                        .into(imageViewQRCodeForUser);//
            } else {

                Glide.with(MyInfoActivity.this)
                        .load(_imageUrlQRCode)
                        .centerInside()//
                        .error(ContextCompat.getDrawable(MyInfoActivity.this, R.drawable.icon_errorfang))
                        .placeholder(ContextCompat.getDrawable(MyInfoActivity.this, R.drawable.icon_errorfang))
                        .fallback(ContextCompat.getDrawable(MyInfoActivity.this, R.drawable.icon_errorfang))
                        .into(imageViewQRCodeForUser);

            }

        } else {

            //如果图片的加载链接为空
            Glide.with(MyInfoActivity.this)
                    .load(_imageUrlQRCode)
                    .centerInside()//
                    .error(ContextCompat.getDrawable(MyInfoActivity.this, R.drawable.icon_errorfang))
                    .placeholder(ContextCompat.getDrawable(MyInfoActivity.this, R.drawable.icon_errorfang))
                    .fallback(ContextCompat.getDrawable(MyInfoActivity.this, R.drawable.icon_errorfang))
                    .into(imageViewQRCodeForUser);

        }


    }

    @Override
    public void gainDatas() {

        //预留下载员工端二维码，或者用户登录完毕，从登录信息内已经给定
        if (NetworkUtils.isConnected()) {

//        String keyWord_upLoad = et_searchInCustomSmall.getText().toString().trim();
            HashMap<String, Object> map = new HashMap<>();
            map.put(Parameterkey.shopInfoId, mSession.getShopInfoId());//,
//            map.put(Parameterkey.customerId, _customerId);//填充搜索出来的这个客户的 唯一id
//            map.put(Parameterkey.pagination, pagination_upLoad);//传递的页码
//            map.put(Parameterkey.pageSize, Parameterkey.pageSize_default);//,搜索关键字

            AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
            addLogUpLoadInfo.setActivity(mActivityInstance);
            addLogUpLoadInfo.setWhat(ConstantApi.WHAT_GETGETCUSTOMERCOUPONFORVERIFY_URL);//请求数字标识
            addLogUpLoadInfo.setUrlPath(ApiService.getGetCustomerCouponForVerify_url);//url地址
            addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);//POST 或者 GET
            addLogUpLoadInfo.setToastToUser(true);//展示给用户的标志
            addLogUpLoadInfo.setHashMapParameter(map);

            //RequestBody.create(JSON.toJSONString(map, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue),
            //                            MediaType.parse(ApiService.HEADER_JSON))
            NetworkManager.getInstance().initRetrofitRxJava()
                    .create(ApiService.class)
                    .getGenerateUrlLinkImgCode()
                    .compose(MyInfoActivity.this.bindUntilEvent(ActivityEvent.DESTROY))//
                    .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<MyInfoQRCode>() {
                        @Override
                        public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
                            super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);

                        }
                    })).doOnSubscribe(new Consumer<Disposable>() {
                        @Override
                        public void accept(Disposable disposable) throws Throwable {

                        }
                    }).subscribe(new Consumer<MyInfoQRCode>() {
                        @Override
                        public void accept(MyInfoQRCode myInfoQRCode) throws Throwable {

//                            {
//                                "code":"20000",
//                                    "data":{
//                                        "largeUrlSuffix":"",
//                                        "smallUrlSuffix":"",
//                                        "url":"http://222.222.17.184:8990/resource/41979474.jpg",
//                                        "urlPrefix":"http://222.222.17.184:8990/resource/",
//                                        "urlSuffix":"41979474.jpg"
//                            },
//                                "message":"success"
//                            }

                            // : 2023-09-06 09:49 加载员工端的二维码信息
                            if (myInfoQRCode != null) {
                                initQRCodeForUser(myInfoQRCode.getUrl());
                            } else {
                                String result = getString(R.string.action_abnormal);
                                PopTip.show(result).iconWarning();
                            }

                        }
                    }, new ErrorConsumer() {

                        @Override
                        protected void error(ApiException apiException) {
                            //页面报错；
                        }
                    });


        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (mCompositeDisposable != null) {
            mCompositeDisposable.clear();
        }

        if (mGlobalSetting != null) {
            mGlobalSetting.onDestroy();
        }

    }

    @Override
    public void methodBack() {

        if (KeyboardUtils.isSoftInputVisible(MyInfoActivity.this)) {
            KeyboardUtils.hideSoftInput(MyInfoActivity.this);
        } else {
            //
        }

        //这里是要携带消息过去的
        ActivityUtils.finishActivity(MyInfoActivity.this);

    }


    /**
     * @param view
     */
    @OnClick(R.id.layouttouxianginfo)
    public void ClickEventInMyInfo(final View view) {

        switch (view.getId()) {

            case R.id.layouttouxianginfo://点击弹窗 上传照片内容。

                if (mAlertView != null && mAlertView.isShowing()) {
                    mAlertView.dismiss();
                    mAlertView = null;//itchen自己添加
                }

                //第二种方式：
                AlertView.Builder builder = new AlertView.Builder().setContext(MyInfoActivity.this)
                        .setStyle(AlertView.Style.ActionSheet)
                        .setTitle(getResources().getString(R.string.upload_image_head))
                        .setMessage(null)
                        .setCancelText(getResources().getString(R.string.cancel))
                        .setOthers(new String[]{
                                getResources().getString(R.string.upload_idcard_takephoto),//拍照
                                getResources().getString(R.string.upload_idcard_pickphoto)})//相册选择
                        .setOnItemClickListener(new OnItemClickListener() {
                            @Override
                            public void onItemClick(Object o, int position) {

                                if (position == 0) {

                                    if (!XXPermissions.isGranted(MyInfoActivity.this, Permission.CAMERA)) {

                                        CommUtils.checkMaterialDialog(materialDialog);

                                        materialDialog = CommUtils.authorityRequest(MyInfoActivity.this, ConstantSign.MATERIALDIALOG_AUTHORITY_CONTENT_CAMERA, new AuthorityCallbackListener() {
                                            @Override
                                            public void doSomeThing() {

                                                CommUtils.checkMaterialDialog(materialDialog);

                                                XXPermissions.with(MyInfoActivity.this)
                                                        // 适配分区存储应该这样写
                                                        //.permission(Permission.Group.STORAGE)
                                                        // 不适配分区存储应该这样写
                                                        .permission(Permission.CAMERA)//
//                                                    .permission(Permission.READ_MEDIA_IMAGES)//
//                                                    .permission(Permission.READ_MEDIA_VIDEO)//
//                                                    .permission(Permission.READ_MEDIA_AUDIO)//
                                                        //).permission(com.hjq.permissions.Permission.MANAGE_EXTERNAL_STORAGE
                                                        .interceptor(new PermissionInterceptor())
                                                        .request(new OnPermissionCallback() {

                                                            @Override
                                                            public void onGranted(@NonNull List<String> permissions, boolean allGranted) {

                                                                if (!allGranted) {
                                                                    return;
                                                                }

                                                                Toaster.show(String.format(getString(R.string.demo_obtain_permission_success_hint),
                                                                        PermissionNameConvert.getPermissionString(MyInfoActivity.this, permissions)));

                                                                if (picCallBackListener != null) {
                                                                    picCallBackListener.clickCamera(0);
                                                                }

                                                            }
                                                        });

                                            }
                                        });

                                    } else {

                                        //如果已经拥有拍照权限，那么直接执行拍照逻辑即可。
                                        if (picCallBackListener != null) {
                                            picCallBackListener.clickCamera(0);
                                        }

                                    }

                                    //LogUtils.d("点击了拍照");
                                } else if (position == 1) {

                                    if (!XXPermissions.isGranted(MyInfoActivity.this, com.hjq.permissions.Permission.READ_MEDIA_IMAGES)) {

                                        CommUtils.checkMaterialDialog(materialDialog);

                                        materialDialog = CommUtils.authorityRequest(mActivityInstance, ConstantSign.MATERIALDIALOG_AUTHORITY_CONTENT_ALBUM, new AuthorityCallbackListener() {

                                            @Override
                                            public void doSomeThing() {

                                                CommUtils.checkMaterialDialog(materialDialog);

                                                XXPermissions.with(MyInfoActivity.this)
                                                        // 适配分区存储应该这样写
                                                        //.permission(Permission.Group.STORAGE)
                                                        // 不适配分区存储应该这样写
//                                                        .permission(com.hjq.permissions.Permission.MANAGE_EXTERNAL_STORAGE)//
                                                        .permission(com.hjq.permissions.Permission.READ_MEDIA_IMAGES)//
                                                        .interceptor(new PermissionInterceptor())
                                                        .request(new OnPermissionCallback() {

                                                            @Override
                                                            public void onGranted(@NonNull List<String> permissions, boolean allGranted) {

                                                                if (!allGranted) {
                                                                    return;
                                                                }

                                                                Toaster.show(String.format(getString(R.string.demo_obtain_permission_success_hint),
                                                                        PermissionNameConvert.getPermissionString(MyInfoActivity.this, permissions)));

                                                                if (picCallBackListener != null) {
                                                                    picCallBackListener.clickAlbum(1);
                                                                }

                                                            }
                                                        });

                                            }
                                        });

                                    } else {

                                        if (picCallBackListener != null) {
                                            picCallBackListener.clickAlbum(1);
                                        }

                                    }

                                }
                            }
                        });

                mAlertView = builder.build();
                mAlertView.setCancelable(false);
                mAlertView.show();

                break;

            default:
                break;
        }
    }


    //================================================================================
    /* 头像文件 */
    private static final String IMAGE_FILE_NAME = "temp_head_image.jpg";
    private static final String CROP_IMAGE_FILE_NAME = "bala_crop.jpg";

    /* 请求识别码 */
    private static final int CODE_GALLERY_REQUEST = 0xa0;
    private static final int CODE_CAMERA_REQUEST = 0xa1;
    private static final int CODE_RESULT_REQUEST = 0xa2;

    // 裁剪后图片的宽(X)和高(Y),480 X 480的正方形。
    private static final int output_X = 500;
    private static final int output_Y = 500;

    private final int PERMISSION_READ_AND_CAMERA = 0;//读和相机权限
    private final int PERMISSION_READ = 1;//读取权限

    /**
     * 针对小米机型的：最后取出的头像地址
     */
    private Uri mUriPath;
    private static final int PRC_PHOTO_PICKER = 1;
    private static final int RC_CHOOSE_PHOTO = 1;

    @AfterPermissionGranted(PRC_PHOTO_PICKER)
    private void choicePhotoWrapper() {


        try {
            //do

            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {

                String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA};

                if (EasyPermissions.hasPermissions(this, perms)) {

                    // 拍照后照片的存放目录，改成你自己拍照后要存放照片的目录。如果不传递该参数的话就没有拍照功能
                    File takePhotoDir = new File(Environment.getExternalStorageDirectory(), ConstantSign.BGA_PHOTO_PICKER_TAKEPHOTO);

                    Intent photoPickerIntent = new BGAPhotoPickerActivity.IntentBuilder(this)
                            .cameraFileDir(takePhotoDir) // 拍照后照片的存放目录，改成你自己拍照后要存放照片的目录。如果不传递该参数的话则不开启图库里的拍照功能
                            .maxChooseCount(1) // 图片选择张数的最大值
                            .selectedPhotos(null) // 当前已选中的图片路径集合
                            .pauseOnScroll(false) // 滚动列表时是否暂停加载图片
                            .build();

                    startActivityForResult(photoPickerIntent, RC_CHOOSE_PHOTO);

                } else {
                    EasyPermissions.requestPermissions(this, StringUtils.getString(R.string.imageselectstr), PRC_PHOTO_PICKER, perms);
                }

            } else {

//                String[] perms = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA};
                String[] perms = {Manifest.permission.READ_MEDIA_IMAGES, Manifest.permission.CAMERA};

                if (EasyPermissions.hasPermissions(this, perms)) {

                    // 拍照后照片的存放目录，改成你自己拍照后要存放照片的目录。如果不传递该参数的话就没有拍照功能
                    File takePhotoDir = new File(Environment.getExternalStorageDirectory(), ConstantSign.BGA_PHOTO_PICKER_TAKEPHOTO);

                    Intent photoPickerIntent = new BGAPhotoPickerActivity.IntentBuilder(this)
                            .cameraFileDir(takePhotoDir) // 拍照后照片的存放目录，改成你自己拍照后要存放照片的目录。如果不传递该参数的话则不开启图库里的拍照功能
                            .maxChooseCount(1) // 图片选择张数的最大值
                            .selectedPhotos(null) // 当前已选中的图片路径集合
                            .pauseOnScroll(false) // 滚动列表时是否暂停加载图片
                            .build();

                    startActivityForResult(photoPickerIntent, RC_CHOOSE_PHOTO);

                } else {
                    EasyPermissions.requestPermissions(this, StringUtils.getString(R.string.imageselectstr), PRC_PHOTO_PICKER, perms);
                }

            }

        } catch (Exception e) {
            //catch
            e.printStackTrace();
        }


    }

//    private void choicePhotoWrapperTrans() {
//
//        // 拍照后照片的存放目录，改成你自己拍照后要存放照片的目录。如果不传递该参数的话就没有拍照功能
//        File takePhotoDir = new File(Environment.getExternalStorageDirectory(), ConstantSign.BGA_PHOTO_PICKER_TAKEPHOTO);
//
//        Intent photoPickerIntent = new BGAPhotoPickerActivity.IntentBuilder(this)
//                .cameraFileDir(takePhotoDir) // 拍照后照片的存放目录，改成你自己拍照后要存放照片的目录。如果不传递该参数的话则不开启图库里的拍照功能
//                .maxChooseCount(1) // 图片选择张数的最大值
//                .selectedPhotos(null) // 当前已选中的图片路径集合
//                .pauseOnScroll(false) // 滚动列表时是否暂停加载图片
//                .build();
//
//        startActivityForResult(photoPickerIntent, RC_CHOOSE_PHOTO);
//
//    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }


    /**
     * 如果是小米手机，那么就从本地选择图片
     */
//    private void methodPicInLoal() {
//
//
//        //再次检查一次权限设置
//        RxPermissions rxPermissions = new RxPermissions(MyInfoActivity.this);
//
//        rxPermissions.request(//
//                        Manifest.permission.CAMERA,//
//                        Manifest.permission.READ_EXTERNAL_STORAGE,//
//                        Manifest.permission.WRITE_EXTERNAL_STORAGE)
//                .subscribe(new Consumer<Boolean>() {//
//                    @Override
//                    public void accept(Boolean aBoolean) throws Exception {
//
//                        if (aBoolean) {
//                            //申请的权限全部允许
//
//                            //LogUtils.d("itchen---小米手机--允许了权限！");
//                            //choseHeadImageFromGallery();
//
//
//                        } else {
//                            //只要有一个权限被拒绝，就会执行
//                            Toast.makeText(MyInfoActivity.this, "未授权权限，部分功能不能使用", Toast.LENGTH_SHORT).show();
//                        }
//                    }
//                });
//
//
//    }


    /**
     * 从本地相册选取图片作为头像
     */
    private void choseHeadImageFromGallery() {
        // 设置文件类型    （在华为手机中不能获取图片，要替换代码）
        /*Intent intentFromGallery = new Intent();
        intentFromGallery.setType("image*//*");
        intentFromGallery.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(intentFromGallery, CODE_GALLERY_REQUEST);*/

        Intent intentFromGallery = new Intent(Intent.ACTION_PICK, null);
        intentFromGallery.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        startActivityForResult(intentFromGallery, CODE_GALLERY_REQUEST);

    }

    /**
     * 裁剪原始的图片
     */
    public void cropRawPhoto(Uri uri) {

        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");

        // 设置裁剪
        intent.putExtra("crop", "true");

        // aspectX , aspectY :宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);

        // outputX , outputY : 裁剪图片宽高
        intent.putExtra("outputX", output_X);
        intent.putExtra("outputY", output_Y);
        intent.putExtra("return-data", true);

        //startActivityForResult(intent, CODE_RESULT_REQUEST); //直接调用此代码在小米手机有异常，换以下代码
        //原始代码
        //String mLinshi = System.currentTimeMillis() + CROP_IMAGE_FILE_NAME;
        //String mLinshi = TimeUtils.getNowMills() + CROP_IMAGE_FILE_NAME;
        //LogUtils.d("itchen----临时头像的名称是：--->"+mLinshi);

        //其他相册的  图片位置是：
        //PathUtils.getExternalAppFilesPath()+File.separator+ TimeUtilSer.getNowPic()+".jpg"
        File mFile = new File(PathUtils.getExternalAppFilesPath(), TimeUtilSer.getNowPic() + ".jpg");
        //mHeadCachePath = mHeadCacheFile.getAbsolutePath();

        //LogUtils.d("itchen----选中的图像路径是----mFile--->" + mFile);
        //itchen----选中的图像路径是----mFile--->/storage/emulated/0/1587801871397bala_crop.jpg
        //itchen----选中的图像路径是----mFile--->/storage/emulated/0/Android/data/com.dgj.propertysmart/files/2020-04-25-16-07-53.jpg
        //itchen----选中的图像路径是----mFile--->/storage/emulated/0/Android/data/com.dgj.propertysmart/files/2020-04-25-16-08-59.jpg

        //不能直接 做裁剪
        //takePicture(mFile.getPath());

        //-------------------------------------------------------------------------------------------
        mUriPath = Uri.parse("file://" + mFile.getAbsolutePath());
        //将裁剪好的图输出到所建文件中
        intent.putExtra(MediaStore.EXTRA_OUTPUT, mUriPath);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        //注意：此处应设置return-data为false，如果设置为true，是直接返回bitmap格式的数据，耗费内存。设置为false，然后，设置裁剪完之后保存的路径，即：intent.putExtra(MediaStore.EXTRA_OUTPUT, uriPath);
        //intent.putExtra("return-data", true);
        intent.putExtra("return-data", false);
        //intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        startActivityForResult(intent, CODE_RESULT_REQUEST);

        //-------------------------------------------------------------------------------------------
    }


    private void openMain(int type) {

        // 拍摄有关设置
        mGlobalSetting = MultiMediaSetting.from(MyInfoActivity.this).choose(MimeType.ofImage());

        CameraSetting cameraSetting = initCameraSetting();
        //设置不要编辑图片
        mGlobalSetting.isImageEdit(false);

        if (type == 1) {

            // 相册,仅仅是图片
            AlbumSetting albumSetting = new AlbumSetting(true)
                    // 支持的类型：图片，视频
                    .mimeTypeSet(MimeType.ofImage())
                    // 是否显示多选图片的数字
                    .countable(true)
                    // 自定义过滤器
                    .addFilter(new GifSizeFilter(320, 320, 5 * BaseFilter.K * BaseFilter.K))
                    // 开启原图
                    .originalEnable(true)
                    // 最大原图size,仅当originalEnable为true的时候才有效
                    .maxOriginalSize(Parameterkey.maxOriginalSize_one);

            //开启相册的功能，相册放在左侧
            mGlobalSetting.albumSetting(albumSetting);

            //开启相机的功能。相机在右侧
            mGlobalSetting.cameraSetting(cameraSetting);

        } else if (type == 0) {

            //开启拍摄功能
            mGlobalSetting.cameraSetting(cameraSetting);

        }

        mGlobalSetting
                // 设置路径和7.0保护路径等等
                .allStrategy(new SaveStrategy(true,//
                        ConstantSign.FILE_PROVIDER, //fileProvider
                        ConstantSign.FOLDER_MIDDLELOW))//
                // for glide-V4
                .imageEngine(new Glide4Engine())
                // 最大5张图片、最大3个视频、最大1个音频
                .maxSelectablePerMediaType(null,//
                        1,//整体设置；
                        1,//
                        1,//
                        0,//
                        0,//
                        0);//
//                .forResult(REQUEST_CODE_CHOOSE);
        mGlobalSetting.forResult(new OnResultCallbackListener() {

            @Override
            public void onResult(@NonNull List<? extends LocalFile> result) {

                for (LocalFile localFile : result) {

//                    LogUtils.d(ConstantSign.LOGCAT_NOMAL, "onResult id:" + localFile.getId());
                    LogUtils.d(ConstantSign.LOGCAT_NOMAL, "onResult 绝对路径:" + localFile.getPath());
                    //args[1] = onResult 绝对路径:/storage/emulated/0/Android/data/com.ygxsk.carhome/files/Pictures/middlelow/IMAGE_20240123_171336391.jpg
//                    LogUtils.d(ConstantSign.LOGCAT_NOMAL, "onResult 旧图路径:" + localFile.getOldPath());

//                    LogUtils.d(ConstantSign.LOGCAT_NOMAL, "onResult 原图路径:" + localFile.getOriginalPath());
                    //args[1] = onResult Uri:content://com.ygxsk.carhome.fileprovider/Pictures/Android/data/com.ygxsk.carhome/files/Pictures/middlelow/IMAGE_20240123_171336391.jpg

//                    LogUtils.d(ConstantSign.LOGCAT_NOMAL, "onResult Uri:" + localFile.getUri());
//                    LogUtils.d(ConstantSign.LOGCAT_NOMAL, "onResult 旧图Uri:" + localFile.getOldUri());
//                    LogUtils.d(ConstantSign.LOGCAT_NOMAL, "onResult 原图Uri:" + localFile.getOriginalUri());
//                    LogUtils.d(ConstantSign.LOGCAT_NOMAL, "onResult 文件大小: " + localFile.getSize());
//                    LogUtils.d(ConstantSign.LOGCAT_NOMAL, "onResult 视频音频长度: " + localFile.getDuration());
//                    LogUtils.d(ConstantSign.LOGCAT_NOMAL, "onResult 是否选择了原图: " + localFile.isOriginal());
//                    if (localFile.isImageOrGif()) {
//                        if (localFile.isImage()) {
//                            LogUtils.d(ConstantSign.LOGCAT_NOMAL, "onResult 图片类型");
//                        } else if (localFile.isImage()) {
//                            LogUtils.d(ConstantSign.LOGCAT_NOMAL, "onResult 图片类型");
//                        }
//                    } else if (localFile.isVideo()) {
//                        LogUtils.d(ConstantSign.LOGCAT_NOMAL, "onResult 视频类型");
//                    } else if (localFile.isAudio()) {
//                        LogUtils.d(ConstantSign.LOGCAT_NOMAL, "onResult 音频类型");
//                    }

                    LogUtils.d(ConstantSign.LOGCAT_NOMAL, "onResult 具体类型:" + localFile.getMimeType());

                    // 某些手机拍摄没有自带宽高，那么我们可以自己获取
//                    if (localFile.getWidth() == 0 && localFile.isVideo()) {
//                        if (localFile.getPath() != null) {
//                            MediaExtraInfo mediaExtraInfo = MediaUtils.getVideoSize(getApplication(), localFile.getPath());
//                            localFile.setWidth(mediaExtraInfo.getWidth());
//                            localFile.setHeight(mediaExtraInfo.getHeight());
//                            localFile.setDuration(mediaExtraInfo.getDuration());
//                        }
//                    }

//                    LogUtils.d(ConstantSign.LOGCAT_NOMAL, "onResult 宽高: " + localFile.getWidth() + "x" + localFile.getHeight());
//                    LogUtils.d(ConstantSign.LOGCAT_NOMAL + "取出的uri路径=", com.zhongjh.common.utils.UriUtils.uriToFile(getApplicationContext(), localFile.getUri()).getPath());
                    //args[1] = /data/user/0/com.ygxsk.carhome/cache/1706001217800

//                    method_uploadNoHttp(localFile.getPath());

                    if (!TextUtils.isEmpty(localFile.getPath())) {

                        takePictureUCrop(localFile.getPath());

                    } else {
                        ToastUtils.showShort(getResources().getString(R.string.path_image_null));
                    }

                }

            }

            @Override
            public void onResultFromPreview(@NonNull List<? extends MultiMedia> result, boolean apply) {

                if (apply) {

                    for (MultiMedia multiMedia : result) {

                        // 绝对路径,AndroidQ如果存在不属于自己App下面的文件夹则无效
                        LogUtils.d(ConstantSign.LOGCAT_NOMAL, "onResult id:" + multiMedia.getId());
                        LogUtils.d(ConstantSign.LOGCAT_NOMAL, "onResult 绝对路径:" + multiMedia.getPath());
                        LogUtils.d(ConstantSign.LOGCAT_NOMAL, "onResult 旧图路径:" + multiMedia.getOldPath());
                        LogUtils.d(ConstantSign.LOGCAT_NOMAL, "onResult 原图路径:" + multiMedia.getOriginalPath());
                        LogUtils.d(ConstantSign.LOGCAT_NOMAL, "onResult Uri:" + multiMedia.getUri());
                        LogUtils.d(ConstantSign.LOGCAT_NOMAL, "onResult 旧图Uri:" + multiMedia.getOldUri());
                        LogUtils.d(ConstantSign.LOGCAT_NOMAL, "onResult 原图Uri:" + multiMedia.getOriginalUri());
                        LogUtils.d(ConstantSign.LOGCAT_NOMAL, "onResult 文件大小: " + multiMedia.getSize());
                        LogUtils.d(ConstantSign.LOGCAT_NOMAL, "onResult 视频音频长度: " + multiMedia.getDuration());
                        LogUtils.d(ConstantSign.LOGCAT_NOMAL, "onResult 是否选择了原图: " + multiMedia.isOriginal());

                        if (multiMedia.isImageOrGif()) {
                            if (multiMedia.isImage()) {
                                LogUtils.d(ConstantSign.LOGCAT_NOMAL, "onResult 图片类型");
                            } else if (multiMedia.isImage()) {
                                LogUtils.d(ConstantSign.LOGCAT_NOMAL, "onResult 图片类型");
                            }
                        } else if (multiMedia.isVideo()) {
//                            LogUtils.d(ConstantSign.LOGCAT_NOMAL, "onResult 视频类型");
                        } else if (multiMedia.isAudio()) {
//                            LogUtils.d(ConstantSign.LOGCAT_NOMAL, "onResult 音频类型");
                        }

                        LogUtils.d(ConstantSign.LOGCAT_NOMAL, "onResult 具体类型:" + multiMedia.getMimeType());
                        LogUtils.d(ConstantSign.LOGCAT_NOMAL, "onResult 宽高: " + multiMedia.getWidth() + "x" + multiMedia.getHeight());
                    }

                }
            }
        });

    }

    /*public static Uri getImageContentUri(Context context, File imageFile) {
        String filePath = imageFile.getAbsolutePath();
        Cursor cursor = context.getContentResolver().query(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                new String[]{MediaStore.Images.Media._ID},
                MediaStore.Images.Media.DATA + "=? ",
                new String[]{filePath}, null);

        if (cursor != null && cursor.moveToFirst()) {
            int id = cursor.getInt(cursor
                    .getColumnIndex(MediaStore.MediaColumns._ID));
            Uri baseUri = Uri.parse("content://media/external/images/media");
            return Uri.withAppendedPath(baseUri, "" + id);
        } else {
            if (imageFile.exists()) {
                ContentValues values = new ContentValues();
                values.put(MediaStore.Images.Media.DATA, filePath);
                return context.getContentResolver().insert(
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            } else {
                return null;
            }
        }
    }*/

    /**
     * 将URI转为图片的路径
     *
     * @param context
     * @param uri
     * @return
     */
    /*public static String getRealFilePath(final Context context, final Uri uri) {
        if (null == uri)
            return null;
        final String scheme = uri.getScheme();
        String data = null;
        if (scheme == null)
            data = uri.getPath();
        else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
            Cursor cursor = context.getContentResolver().query(uri,
                    new String[]{MediaStore.Images.ImageColumns.DATA}, null, null, null);
            if (null != cursor) {
                if (cursor.moveToFirst()) {
                    int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                    if (index > -1) {
                        data = cursor.getString(index);
                    }
                }
                cursor.close();
            }
        }
        return data;
    }*/


}
